package com.freeter.modules.controller;

import com.freeter.modules.gjs.entity.MstrSite;
import com.freeter.modules.gjs.service.MstrSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/mstr-site")
@CrossOrigin(origins = "*")
public class MstrSiteController {

    @Autowired
    private MstrSiteService mstrSiteService;

    @GetMapping
    public ResponseEntity<List<MstrSite>> getAllSites() {
        List<MstrSite> sites = mstrSiteService.getAllSites();
        return ResponseEntity.ok(sites);
    }

    @GetMapping("/{id}")
    public ResponseEntity<MstrSite> getSiteById(@PathVariable Long id) {
        MstrSite site = mstrSiteService.getSiteById(id);
        if (site != null) {
            return ResponseEntity.ok(site);
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/code/{siteCode}")
    public ResponseEntity<MstrSite> getSiteByCode(@PathVariable String siteCode) {
        MstrSite site = mstrSiteService.getSiteByCode(siteCode);
        if (site != null) {
            return ResponseEntity.ok(site);
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping
    public ResponseEntity<MstrSite> createSite(@RequestBody MstrSite site) {
        MstrSite createdSite = mstrSiteService.createSite(site);
        return ResponseEntity.ok(createdSite);
    }

    @PutMapping("/{id}")
    public ResponseEntity<MstrSite> updateSite(@PathVariable Long id, @RequestBody MstrSite site) {
        try {
            MstrSite updatedSite = mstrSiteService.updateSite(id, site);
            return ResponseEntity.ok(updatedSite);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSite(@PathVariable Long id) {
        mstrSiteService.deleteSite(id);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/code/{siteCode}")
    public ResponseEntity<Void> deleteSiteByCode(@PathVariable String siteCode) {
        mstrSiteService.deleteSiteByCode(siteCode);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/status/{status}")
    public ResponseEntity<List<MstrSite>> getSitesByStatus(@PathVariable String status) {
        List<MstrSite> sites = mstrSiteService.getSitesByStatus(status);
        return ResponseEntity.ok(sites);
    }
}